package com.icss.ah.logistic.service;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.icss.ah.base.util.DateUtils;
import com.icss.ah.base.util.ResourceLoader;
import com.icss.ah.orderList.bean.OrderHeadBean;
import com.quartz.bean.ScheduleJob;
import com.quartz.util.QuartzCallUtil;
import com.wx.util.WxUtil;

@Service
@Transactional
public class LogisticService {
	private final Logger errlog = Logger.getLogger("E");
	private final Logger infolog = Logger.getLogger("I");
	@Autowired
	private SqlSessionTemplate sqlSessionTemplate;
	
	/**
	 * 查询订单 通过订单号
	 * @param modelKey
	 * @param map
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public List getOrderByOrderNo(String modelKey,HashMap map) {
		List data = new ArrayList();
		try {
			data = sqlSessionTemplate.selectList(modelKey,map);
		} catch (Exception ex) {
			ex.printStackTrace();
		} 
		return data==null?new ArrayList():data;
	}
	
	/**
	 * 写入物流信息
	 * @param modelKey
	 * @param map
	 */
	public boolean addLogisticInfo(String modelKey,Map<String, Object> map) {
		boolean result=false;
		try {
			sqlSessionTemplate.insert(modelKey,map);
			result = true;
		} catch (Exception ex) {
			ex.printStackTrace();
			result = false;
		} 
		return result;
	}
	
	
	
	public boolean addLogisticInfoNew(HashMap<String,Object> map) {
		boolean result=false;
		try {
			sqlSessionTemplate.insert("LogisticBean.addLogisticInfo", map);
			HashMap data = sqlSessionTemplate.selectOne("LogisticBean.getLogisitInfo", map);//获取物流信息
			sendTemplate(map,data);//发送模版消息
			result = true;
		} catch (Exception ex) {
			ex.printStackTrace();
			result = false;
		} 
		return result;
	}
	
	/**
	 * 发送模版消息(wj)
	 * @param shopId
	 * @param corpId
	 * @param orderNo
	 */
	public void sendTemplate(HashMap<String,Object> map,HashMap data){
		String openId = data.get("USER_CODE").toString();//用户编码
		String orderUuid = data.get("ORDER_UUID").toString();//
		//String openId = "o6ATZsntVyGg3rIpHxNhIAd18N3Q";
		String codeName = data.get("CODE_NAME").toString();//物流状态
		String logisticsInfo = data.get("LOGISTICS_INTO").toString();//物流信息
		String remark = data.get("REMARK").toString();//备注 
		if(remark==null||remark.equals("")){
			remark = "祝您生活愉快";
		}
		String orderNo = data.get("ORDER_NO").toString();//订单号
		String logisticsTime = data.get("LOGISTICS_TIME").toString();//物流时间
		if(logisticsTime.length()>19){
			logisticsTime = logisticsTime.substring(0, 19);
		}
		
		String templateId = map.get("templateId").toString();//templateId(模版id)
		String corpSecret = map.get("corpSecret").toString();//corpSecret(开发者凭据)
		String corpId = map.get("CORP_ID").toString();//corpId(公众号id)
		String corpKey = map.get("corpKey").toString();//corpKey(公众号关键字)
		String TMP_ORDER_URL = map.get("TMP_ORDER_URL").toString();//
		
		
		String scope = "snsapi_base";
		String url = TMP_ORDER_URL+orderUuid;
		url = URLEncoder.encode(url);
		String urlCode = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+corpId+"&redirect_uri="+url+"&response_type=code&scope="+scope+"&state="+corpKey+"#wechat_redirect";
		
		String token = WxUtil.getTokenFromServer(corpId, corpSecret);
		String postData = "";
		postData += "{";
		postData += "   \"touser\":\""+openId+"\",";
		postData += "   \"template_id\":\""+templateId+"\",";
		postData += "   \"url\":\""+urlCode+"\",";
		postData += "   \"data\":{";
		postData += "	   \"first\": {";
		postData += "	       \"value\":\"尊敬的用户您好\",";
		postData += "	       \"color\":\"\"";
		postData += "	   },";
		postData += "	   \"keyword1\": {";
		postData += "	       \"value\":\""+orderNo+"\",";
		postData += "	       \"color\":\"#7F7F7F\"";
		postData += "	   },";
		postData += "	   \"keyword2\": {";
		postData += "	       \"value\":\""+codeName+"\",";
		postData += "	       \"color\":\"#7EC0EE\"";
		postData += "	   },";
		postData += "	   \"keyword3\": {";
		postData += "	       \"value\":\""+logisticsInfo+"\",";
		postData += "	       \"color\":\"#7F7F7F\"";
		postData += "	   },";
		postData += "	   \"keyword4\": {";
		postData += "	       \"value\":\""+logisticsTime+"\",";
		postData += "	       \"color\":\"#7F7F7F\"";
		postData += "	   },";
		postData += "	   \"remark\":{";
		postData += "	       \"value\":\""+remark+"\",";
		postData += "	       \"color\":\"\"";
		postData += "	   }";
		postData += "   }";
		postData += "}";
		com.alibaba.fastjson.JSONObject jsonObject = WxUtil.templateSend(token, postData);
		System.out.println("模版消息发送============================"+jsonObject.toJSONString());
		//LogUtils.info(jsonObject.toJSONString());
		
	}
	/**
	 * 发送模版消息(wj)
	 * @param shopId
	 * @param corpId
	 * @param orderNo
	 */
	public void sendTemplateDispatcher(HashMap<String,Object> hm){
		try {
			HashMap dispatcherInfo = sqlSessionTemplate.selectOne("LogisticBean.queryDispatcherInfo", hm);//获取送货员信息
			infolog.info("logisticService|sendTemplateDispatcher|dispatcherInfo:"+dispatcherInfo);
			HashMap consumer = sqlSessionTemplate.selectOne("LogisticBean.queryOrderConsumerInfo", hm);//获取送货员信息
			infolog.info("logisticService|sendTemplateDispatcher|consumer:"+consumer);
			consumer = consumer == null ? new HashMap() : consumer;
			if(dispatcherInfo!=null&&!dispatcherInfo.isEmpty()){
				String openId = dispatcherInfo.get("USER_CODE").toString();
				
				String templateId = hm.get("templateIdD").toString();
				String corpSecret = hm.get("corpSecret").toString();//corpSecret(开发者凭据)
				String corpId = hm.get("CORP_ID").toString();//corpId(公众号id)
				String corpKey = hm.get("corpKey").toString();//corpKey(公众号关键字)
				String TMP_DISPATCHER_URL = hm.get("TMP_DISPATCHER_URL").toString();//
				
				String consumerName = consumer.get("CON_NAME") == null ? "" : consumer.get("CON_NAME").toString();
				String consumerTel = consumer.get("CON_TEL") == null ? "" : consumer.get("CON_TEL").toString();
				String province_name = consumer.get("PROVINCE_NAME") == null ? "" : consumer.get("PROVINCE_NAME").toString();
				String city_name = consumer.get("CITY_NAME") == null ? "" : consumer.get("CITY_NAME").toString();
				String county_name = consumer.get("COUNTY_NAME") == null ? "" : consumer.get("COUNTY_NAME").toString();
				String con_address = consumer.get("CON_ADDRESS") == null ? "" : consumer.get("CON_ADDRESS").toString();
				String sum_sell_amount = consumer.get("SUM_SELL_AMOUNT") == null ? "0" : consumer.get("SUM_SELL_AMOUNT").toString();
				String product_name = consumer.get("PRODUCT_NAME") == null ? "" : consumer.get("PRODUCT_NAME").toString();
				String consumerAddress = province_name+city_name+county_name+con_address;
				
				
				String scope = "snsapi_base";
				String url = TMP_DISPATCHER_URL;
				url = URLEncoder.encode(url);
				String urlCode = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+corpId+"&redirect_uri="+url+"&response_type=code&scope="+scope+"&state="+corpKey+"#wechat_redirect";
				
				String token = WxUtil.getTokenFromServer(corpId, corpSecret);
				String postData = "";
				postData += "{";
				postData += "   \"touser\":\""+openId+"\",";
				postData += "   \"template_id\":\""+templateId+"\",";
				postData += "   \"url\":\""+urlCode+"\",";
				postData += "   \"data\":{";
				postData += "	   \"first\": {";
				postData += "	       \"value\":\"亲爱的送货员，您有新的送货任务\",";
				postData += "	       \"color\":\"\"";
				postData += "	   },";
				postData += "	   \"keyword1\": {";
				postData += "	       \"value\":\""+consumerName+"\",";
				postData += "	       \"color\":\"#7F7F7F\"";
				postData += "	   },";
				postData += "	   \"keyword2\": {";
				postData += "	       \"value\":\""+consumerTel+"\",";
				postData += "	       \"color\":\"#7EC0EE\"";
				postData += "	   },";
				postData += "	   \"keyword3\": {";
				postData += "	       \"value\":\""+consumerAddress+"\",";
				postData += "	       \"color\":\"#7F7F7F\"";
				postData += "	   },";
				postData += "	   \"keyword4\": {";
				postData += "	       \"value\":\""+product_name+"等\",";
				postData += "	       \"color\":\"#7F7F7F\"";
				postData += "	   },";
				postData += "	   \"keyword5\": {";
				postData += "	       \"value\":\""+sum_sell_amount+"\",";
				postData += "	       \"color\":\"#7F7F7F\"";
				postData += "	   },";
				postData += "	   \"remark\":{";
				postData += "	       \"value\":\"请及时送达，谢谢！\",";
				postData += "	       \"color\":\"\"";
				postData += "	   }";
				postData += "   }";
				postData += "}";
				com.alibaba.fastjson.JSONObject jsonObject = WxUtil.templateSend(token, postData);
				infolog.info("logisticService|sendTemplateDispatcher|jsonObject:"+jsonObject.toString());
			}
		} catch (Exception e) {
		}
		
	}
	/*
	 * 添加自动订单确认收货
	 */
	public void autoConfirmOrder(OrderHeadBean orderHeadBean){
		try{
			String clientUrl = ResourceLoader.getInstance("icss").getString("clientUrl"); 
			String orderNo = orderHeadBean.getOrderNo();
			Long lastTimestamp = System.currentTimeMillis();
			Long deadlineTimeConfirm = lastTimestamp + 24 * 60 * 60 * 1000 * 7;//自动订单确认收货时限为24*7小时
			//传参用
			HashMap<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("corpId", orderHeadBean.getCorpId());
			paramMap.put("userCode", orderHeadBean.getUserCode());
			paramMap.put("orderUuid", orderHeadBean.getOrderUuid());
			paramMap.put("shopId", orderHeadBean.getShopId());
			//未到截止时间，新增定时任务，由定时任务关闭订单
			//31 16 14 18 9 ? 2017   2017年9月18日14点16分31秒
			String cronExp = DateUtils.formatTime(deadlineTimeConfirm, "ss mm HH dd MM ? yyyy");
			ScheduleJob scheduleJob = new ScheduleJob();
			scheduleJob.setJobName("自动订单确认收货" + orderNo);
			scheduleJob.setCronExpression(cronExp);
			scheduleJob.setJobType(1);
			scheduleJob.setNotifyUrl(clientUrl + "/trigger/confirmOrder.do");
			scheduleJob.setParamMap(paramMap);
			QuartzCallUtil.addJob(scheduleJob);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	public HashMap queryStatus(HashMap map) {
		HashMap resMap = new HashMap();
		try {
			resMap = sqlSessionTemplate.selectOne("LogisticBean.queryStatus", map);
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return resMap;
	}

	
}
